package com.zhaolixiang.slidetabview

import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Color
import android.os.Handler
import android.util.AttributeSet
import android.util.Log
import android.view.MotionEvent
import android.widget.HorizontalScrollView
import android.widget.LinearLayout
import android.widget.TextView
import java.util.jar.Attributes
import android.support.v4.view.ViewConfigurationCompat
import android.view.ViewConfiguration




/**
 * Created by Administrator on 2018/1/3.
 */
class SlideTabLinearLayout3 : HorizontalScrollView {
    //当前是Horizontal滑动
    private var IsHorizontalScrolling=false
    private var IsViewPageScrolling=false
    private var leftAndRightMinWidth = 0
    //正常字体颜色:ffffff
    private val NormalColor = 0xff95ccff
    //变换后的颜色：
    private val ChangedColor = 0xffffffff
    //正常字体大小:18sp,单位px
    private var NormalSize: Float = 18f
    //变换后字体大小：30sp，单位px
    private var ChangedSize = 30f;
    //点断是否初始化完成
    private var InitFinish = false;
    //最大值
    private var MaxValue = 0
    private var MinValue = 0
    /**
     * 判定为拖动的最小移动像素数
     */
    private var mTouchSlop: Int = 0
    //之前的位置，用来和最小移动像素比较，防止抖动
    private var PreviousMoveX=0

    private fun getNowColor(value: Float, width: Float, fromColor: Long, toColor: Long): Int {
        var value=value;
        if(IsHorizontalScrolling && width-value<=mTouchSlop){
            value=width
        }
        //A--NormalColor
        val NormalColorA: Float = fromColor.shr(24).toFloat()
        //R--NormalColor
        val NormalColorR: Float = (fromColor.shr(16) and 0xff).toFloat()
        //G--NormalColor
        val NormalColorG: Float = (fromColor.shr(8) and 0xff).toFloat()
        //B--NormalColor
        val NormalColorB: Float = (fromColor and 0xff).toFloat()

        //A--ChangedColor
        val ChangedColorA: Float = (toColor.shr(24)).toFloat()
        //R--ChangedColor
        val ChangedColorR: Float = (toColor.shr(16) and 0xff).toFloat()
        //G--ChangedColor
        val ChangedColorG: Float = (toColor.shr(8) and 0xff).toFloat()
        //B--ChangedColor
        val ChangedColorB: Float = (toColor and 0xff).toFloat()


        //A--ResultColor
        //val ResultColorA=NormalColorA+((ChangedColorA-NormalColorA)/width)*value

        //R--ResultColor
        val ResultColorR = NormalColorR + ((ChangedColorR - NormalColorR) / width) * value
        Log.e("ResultColorR", "NormalColorR:$NormalColorR---ChangedColorR:$ChangedColorR---width:$width" +
                "---value:$value---ResultColorR:$ResultColorR")
        //G--ResultColor
        val ResultColorG: Float = (NormalColorG + ((ChangedColorG - NormalColorG) / width) * value)
        Log.e("我阿里计算1：", "" + ((ChangedColorG - NormalColorG)))
        Log.e("我阿里计算2：", "" + ((ChangedColorG - NormalColorG) / width))
        Log.e("我阿里计算3：", "" + (((ChangedColorG - NormalColorG) / width) * value))
        Log.e("我阿里计算4：", "" + (255.0 - (255.0 - 149.0) / 288.0 * 89.0))
        Log.e("ResultColorG", "NormalColorG:$NormalColorG---ChangedColorG:$ChangedColorG---width:$width" +
                "---value:$value---ResultColorG:$ResultColorG")
        //V--ResultColor
        val ResultColorB = NormalColorB + ((ChangedColorB - NormalColorB) / width) * value
        Log.e("ResultColorB", "NormalColorB:$NormalColorB---ChangedColorB:$ChangedColorB---width:$width" +
                "---value:$value---ResultColorB:$ResultColorB")

        /*
        * NormalColorA.toLong().shl(24)) or
                (ResultColorR.toLong().shl(16)) or
                (ResultColorG.toLong().shl(8)) or
                ResultColorB.toLong()*/
        //r,g,b,a
        /* return Color.valueOf((NormalColorA.toLong().shl(24)) or
                 (ResultColorR.toLong().shl(16)) or
                 (ResultColorG.toLong().shl(8)) or
                 ResultColorB.toLong())*/

        return Color.argb(NormalColorA.toInt(), ResultColorR.toInt(), ResultColorG.toInt(), ResultColorB.toInt())
    }

    private fun getNowSize(value: Float, width: Float, fromSize: Float, toSize: Float): Float {
        var value=value;
        if(IsHorizontalScrolling && width-value<=mTouchSlop){
            value=width
        }
        Log.e("获取现在的大小", "" + (((toSize - fromSize) / width) * value + fromSize))
        return ((toSize - fromSize) / width) * value + fromSize

    }

    //滑动的x坐标值
    private var perviousX = 0f

    /**
     * 滑动事件
     */
    override fun fling(velocityY: Int) {
        super.fling(velocityY / 5)
    }

    /**
     * 滚动状态:
     * IDLE=滚动停止
     * TOUCH_SCROLL=手指拖动滚动
     * FLING=滚动
     */
    enum class ScrollType {
        IDLE, TOUCH_SCROLL, FLING
    };
    /**
     * 滚动方向：direction
     */
    enum class Direction {
        LEFT, RIGHT, NON
    }

    //初始化，未设置
    private var direction = Direction.NON

    /**
     * 当前滚动状态
     */
    private var scrollType = ScrollType.IDLE
    private var mScrollViewListener: ScrollViewListener? = null
    private lateinit var mHandler: Handler
    /**
     * 停止滚动后记录当前滚动的距离
     */
    private var currentX = -9999999
    private var width1 = 0;
    private var width2 = 0;
    private var width3 = 0;
    private var width4 = 0;
    private var viewPagePosition=1;
    private var viewPagepositionOffset=0f

    interface ScrollViewListener {
        fun onScrollChanged(scrollType: ScrollType)
    }

    constructor(context: Context) : super(context)
    constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
    constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr)

    init {
        /* //设置默认字体
         NormalSize=ForScreen.sp2pxReturnFloadt(this.context,18f)
         //设置变换后的字体
         ChangedSize=ForScreen.sp2pxReturnFloadt(context,30f)*/

        Log.e("获取字体", "NormalSize$NormalSize..ChangedSize$ChangedSize")
        mHandler = Handler();
        mScrollViewListener = object : ScrollViewListener {
            override fun onScrollChanged(scrollType: ScrollType) {
                if (scrollType == ScrollType.IDLE) {
                    InitFinish = true
                    Log.e("滑动亭子", "最终效果" + currentX)
                    if(onScrollEnd!=null){
                        onScrollEnd!!.end(currentX)
                    }

                    judge(currentX)

                }
            }
        }
        val configuration = ViewConfiguration.get(context)
        // 获取TouchSlop值
        mTouchSlop = ViewConfigurationCompat.getScaledPagingTouchSlop(configuration)
        Log.e("判定为移动的最小单位",mTouchSlop.toString())
    }

    private fun mySmoothScrollTo(x: Int, y: Int) {
        mHandler.post(scrollRunnable);
        smoothScrollTo(x, y)
    }

    //设置左右两边边至少剩余的宽度
    public fun setMinWidth(w1: Int, w2: Int, w3: Int, w4: Int) {
        MaxValue = w1
        MinValue = w2
        width1 = w2
        width2 = w2
        width3 = w2
        width4 = w2
        leftAndRightMinWidth = 4*w2
        mySmoothScrollTo(leftAndRightMinWidth, 0)

        //1312
        Log.e("设置左边最少距离", "" + leftAndRightMinWidth + "---" + scaleX
                + "width1$width1、width2$width2、width3$width3、width4$width4、MaxValue$MaxValue、MinValue$MinValue")


    }
    override fun onScrollChanged(x: Int, y: Int, oldX: Int, oldY: Int) {
        Log.e("滑动了888888", "onScrollChanged$x---$oldX---PreviousMoveX:$PreviousMoveX")
        onMoveChangeStyle(x)
       /* if(x-PreviousMoveX>mTouchSlop){
            PreviousMoveX=x
            onMoveChangeStyle(x)
        }*/


        if (leftAndRightMinWidth > 0) {
            Log.e("滑动了2", "onScrollChanged$x---$oldX")
            //只有当初始化后才有效果
            if (x < leftAndRightMinWidth) {
                Log.e("滑动了3", "onScrollChanged$x---$oldX")
                //如果向左滑动了，就重新添加一组数据到左边
                //  leftAdd()
                if (InitFinish) {
                    mySmoothScrollTo(x + leftAndRightMinWidth, 0)
                } else {

                }
                /*
                if(oldX==0){
                    mySmoothScrollTo(leftAndRightMinWidth,0)
                }else{
                   // deleteRight()
                    //addLeft()

                }*/

            } else if (x > (addRightCount - 5) * leftAndRightMinWidth) {
                Log.e("滑动了4", "onScrollChanged$x---$oldX")
                //这里会出现滑动卡顿现象
                //mySmoothScrollTo(x-leftAndRightMinWidth,0)
                //deleteLeft()
                addRight()
                addRight()
                addRight()
                addRight()
                addRight()
                addRight()
                addRight()
                addRight()
                addRight()
                addRight()
            }
        }
        Log.e("滑动了5", "onScrollChanged$x---$oldX")

        super.onScrollChanged(x, y, oldX, oldY)
    }

    private var addRightCount = 7;
    private fun addRight() {
        addRightCount++
        AddView().addRight(context, (this.getChildAt(0)) as LinearLayout, NormalSize)
    }

    private fun judge(scrollX2: Int) {
        var scrollX = scrollX2
        //需要转换一下：
        Log.e("judge", "scrollX$scrollX")
        val yushuo: Int = (scrollX / MinValue).toInt()
        val cha = scrollX - MinValue * yushuo
        if(cha>MinValue/2){
            //说明移动了一半多：移动到下一个
            smoothScrollTo((yushuo + 1) * MinValue, 0)
            onMoveChangeStyle((yushuo + 1) * MinValue)
        }else{
            //移动到上一个
            smoothScrollTo(yushuo * MinValue, 0)
            onMoveChangeStyle(yushuo * MinValue)
        }
    }

    /**
     * 滚动监听runnable
     */
    private val scrollRunnable = object : Runnable {
        override fun run() {
            if (scrollX == currentX) {
                //滚动停止,取消监听线程
                scrollType = ScrollType.IDLE
                if (mScrollViewListener != null) {
                    mScrollViewListener!!.onScrollChanged(scrollType)
                }
                mHandler.removeCallbacks(this)
                return
            } else {
                Log.e("手指离开屏幕,但是view还在滚动", "手指离开屏幕,但是view还在滚动" + currentX)
                //手指离开屏幕,但是view还在滚动
                scrollType = ScrollType.FLING
                if (mScrollViewListener != null) {
                    mScrollViewListener!!.onScrollChanged(scrollType)
                }
            }
            currentX = scrollX
            Log.e("停止滚动后记录当前滚动的距离", "" + currentX)
            //滚动监听间隔:milliseconds
            mHandler.postDelayed(this, 50)
        }
    }
    public fun deleteOnToucheEvent(ev: MotionEvent){
        Log.e("处理阶段","${ev.action}--${ev.x}--${ev.y}")
        when (ev.action) {
            MotionEvent.ACTION_DOWN -> {
                //按下开始滑动
                perviousX = ev.x
            }
            MotionEvent.ACTION_MOVE -> {
                //触摸移动中
                if (ev.x > perviousX) {
                    //想右移动
                    direction = Direction.RIGHT
                } else if (ev.x < perviousX) {
                    //向左移动
                    direction = Direction.LEFT
                } else {
                    direction = Direction.NON
                }
                this.scrollType = ScrollType.TOUCH_SCROLL
                if (mScrollViewListener != null) {
                    mScrollViewListener!!.onScrollChanged(scrollType);
                }
                mHandler.removeCallbacks(scrollRunnable);
                val yidong=-((ev.x-perviousX)*MinValue/ForScreen.getWindowsWidth(context)).toInt()
                if(Math.abs(yidong)>1){
                    smoothScrollBy(yidong,0)
                    perviousX = ev.x
                }

            }
            MotionEvent.ACTION_UP -> {
                //手指离开时
                mHandler.post(scrollRunnable);
            }
        }
    }

    private var onScrollEnd:OnScrollEnd?=null
    public  fun setOnScrollEnd(l: OnScrollEnd) {
        onScrollEnd=l
    }
    override fun onTouchEvent(ev: MotionEvent): Boolean {
        when (ev.action) {
            MotionEvent.ACTION_DOWN -> {
                //按下开始滑动
                perviousX = ev.x
            }
            MotionEvent.ACTION_MOVE -> {
                //触摸移动中
                if (ev.x > perviousX) {
                    //想右移动
                    direction = Direction.RIGHT
                } else if (ev.x < perviousX) {
                    //向左移动
                    direction = Direction.LEFT
                } else {
                    direction = Direction.NON
                }
                this.scrollType = ScrollType.TOUCH_SCROLL
                if (mScrollViewListener != null) {
                    mScrollViewListener!!.onScrollChanged(scrollType);
                }
                mHandler.removeCallbacks(scrollRunnable);
            }
            MotionEvent.ACTION_UP -> {
                //手指离开时
                mHandler.post(scrollRunnable);
            }
        }
        return super.onTouchEvent(ev)
    }

    //移动过程中改变对应大小
    private fun onMoveChangeStyle(scrollX2: Int) {
        var scrollX = scrollX2
        Log.e("changeSize", "scrollX$scrollX")
        val yushuo: Int = (scrollX / MinValue).toInt()
        val cha = scrollX - MinValue * yushuo
        getNowIdAndSetLeftAndRight(yushuo, cha)
    }

    private fun getNowIdAndSetLeftAndRight(sq: Int, cha: Int) {
        Log.e("gggggg", "sq:$sq---cha:$cha、width1$width1、width2$width2、width3$width3、width4$width4")

        setTextColorByIds(sq, getNowColor(cha.toFloat(), width1.toFloat(), ChangedColor, NormalColor))
        setTextColorByIds(sq + 1, getNowColor(cha.toFloat(), width1.toFloat(), NormalColor, ChangedColor))

        setTextSizeByIds(sq, getNowSize(cha.toFloat(), width1.toFloat(), ChangedSize, NormalSize))
        setTextSizeByIds(sq + 1, getNowSize(cha.toFloat(), width1.toFloat(), NormalSize, ChangedSize))
         val view =this.getChildAt(0) as LinearLayout
        for(j in 0 until view.childCount){
            if(j!=sq && j!=(sq+1)){
                val item = (this.getChildAt(0) as LinearLayout).getChildAt(j) as TextView
                item.setTextColor(Color.parseColor("#95ccff"))
                item.setTextSize(NormalSize)
            }
        }

    }
    private fun setTextColorByIds(ids: Int, color: Int) {
        Log.e("设置颜色了", "ids:$ids---color:$color---${Color.parseColor("#95ccff")}")
        val item = (this.getChildAt(0) as LinearLayout).getChildAt(ids) as TextView
        item.setTextColor(color)
    }

    private fun setTextSizeByIds(ids: Int, size: Float) {
        Log.e("设置大小了", "ids:$ids---size:$size")
        val item = (this.getChildAt(0) as LinearLayout).getChildAt(ids) as TextView
        item.textSize = size
        Log.e("设置大小后重新获取大小", "item.measuredWidth：" + item.measuredWidth)
    }

    public fun onViewPageScroll(position: Int, positionOffset: Float, positionOffsetPixels: Int,currentLast:Int){
        // arg0 :当前页面，及你点击滑动的页面；arg1:当前页面偏移的百分比；arg2:当前页面偏移的像素位置
        mHandler.removeCallbacks(scrollRunnable);
        //currentLast:循环了几圈
        /*val cha=position-viewPagePosition
        if(cha==1){

        }else if(cha==-1){
            //1-->0
            if(positionOffset>viewPagepositionOffset){
                //想有滑动
            }else{
                //向左滑动
            }
        }else if(cha==4) {
            //0-->4
            if(positionOffset>viewPagepositionOffset){
                //想有滑动
            }else{
                //向左滑动
            }
        }else if(cha==-4){
            //5--1
            if(positionOffset>viewPagepositionOffset){
                //想有滑动
            }else{
                //向左滑动
            }
        }*/
        Log.e("产看滚动距离","positionOffset:$positionOffset---viewPagepositionOffset:$viewPagepositionOffset" +
                "--差${(positionOffset-viewPagepositionOffset)*MinValue}---mTouchSlop$mTouchSlop---" +
                "viewPagePosition$viewPagePosition---position$position")
        smoothScrollTo((currentX+(positionOffset-viewPagepositionOffset)*MinValue*10).toInt(),0)
        viewPagePosition=position
        viewPagepositionOffset=positionOffset
        /*if(position!=viewPagePosition){
            viewPagePosition=position
            viewPagepositionOffset=positionOffset

        }else{
            smoothScrollTo((currentX+(positionOffset-viewPagepositionOffset)*MinValue*10).toInt(),0)
            viewPagePosition=position
            viewPagepositionOffset=positionOffset

            *//*if(Math.abs((positionOffset-viewPagepositionOffset)*MinValue)>5){
                smoothScrollTo((currentX+(positionOffset-viewPagepositionOffset)*MinValue).toInt(),0)
                viewPagePosition=position
                viewPagepositionOffset=positionOffset
            }*//*

        }*/

        //mySmoothScrollTo(((position-1)*MinValue+positionOffset*MinValue+currentLast*leftAndRightMinWidth).toInt(),0)

    }
    //底部viewpage滑动结束，实现和顶部的同步
    public fun onViewPageStop(page:Int){
        if(MinValue==0) return
        //0,1,2,3,4,5
        //4,1,2,3,4,1
        var page=page
        if(page==0) page=4
        if(page==5) page=1
        //根据现在的滑动偏移量，求出最近一个的位置
        val yushuo: Int = (scrollX / MinValue).toInt()
        val zu:Int=scrollX/MinValue/4
        //可能存在的位置：
        val location1=zu*4*MinValue+(page-1)*MinValue
        val location2=(zu+1)*4*MinValue+(page-1)*MinValue
        if(Math.abs(scrollX-location1)>Math.abs(scrollX-location2)){
            //说明2位置比较准确
            mySmoothScrollTo(location2,0)
        }else{
            //说明位置1比较准确
            mySmoothScrollTo(location1,0)
        }
    }

    override fun onInterceptTouchEvent(ev: MotionEvent): Boolean {
        when (ev.action) {
            MotionEvent.ACTION_DOWN -> {

            }
            MotionEvent.ACTION_MOVE -> {
            }
        }
        return false
       // return super.onInterceptTouchEvent(ev)
    }
}